package com.zydl.f9164m.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.suke.widget.SwitchButton;
import com.zydl.f9164m.R;
import com.zydl.f9164m.basis.BasisFragment;
import com.zydl.f9164m.basis.Constants;
import com.zydl.f9164m.bean.ParamListData;
import com.zydl.f9164m.eventbus.FragmentChangeMessage;
import com.zydl.f9164m.util.CountDown;
import com.zydl.f9164m.util.EditTextUtil;
import com.zydl.f9164m.util.SoftKeyBoardListener;
import com.zydl.f9164m.util.SubstringUtil;
import com.zydl.f9164m.view.PopHandle;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.BleUtils;
import my.LogUtil;

public class BeidouFragment extends BasisFragment {

    static BeidouFragment fragment;

    public static BeidouFragment newInstance() {
        if (fragment == null) {
            fragment = new BeidouFragment();
        }
        return fragment;
    }

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    MyAdapter adapter;
    private ArrayList<ParamListData> showList;
    ArrayList<ParamListData> originalList;
    public static int SUBMIT = 75;

    private boolean isFinish = false;

    private CountDown mCountDownTimer;
    private static final long MAX_TIME = 11 * 1000;
    private StringBuffer saveResult = new StringBuffer();


    private PopHandle popHandle;
    private int subPosition = 0;

    private Handler submitHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 75://75提交
                    isFinish = false;
                    if (subPosition < showList.size()) {
                        initSettingSaveThred(subPosition);
                        subPosition++;
                    } else {
                        BleUtils.stopNotify();
                        isFinish = true;
                        originalList.clear();
                        originalList.addAll(showList);
                        dismissProgress();
                        mCountDownTimer.cancel();
                        if (!TextUtils.isEmpty(saveResult.toString())) {
                            if (popHandle == null) {
                                popHandle = new PopHandle(mContext, "tips_fail", "错误信息", saveResult.toString());
                            }
                            popHandle.show();
                        } else {
                            showToast("保存成功");
                        }
                    }
                    break;
                case 76:  //检查是否传输完毕
                    if (!isFinish) {
                        showToast("设置失败，请重试");
                        dismissProgress();
                        BleUtils.stopNotify();
                    }
                    break;
            }

        }
    };


    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.fragment_center);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        initCountDownTimer();
    }

    public void initCountDownTimer() {
        mCountDownTimer = new CountDown();
        mCountDownTimer.setMillisInFuture(MAX_TIME);
        mCountDownTimer.setCountdownInterval(1000);
        mCountDownTimer.setCountDownListener(new CountDown.CountDownListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
                submitHandler.sendEmptyMessage(Constants.CHECK_FINISH);
                //这时候可以做30秒的计时操作
//                submitHandler.sendEmptyMessageDelayed(Constants.CHECK_FINISH, 20000);
//                          submitHandler.postDelayed(Constants.SUBMIT,20000);   //20秒后执行
            }

            @Override
            public void onTick(long millisUntilFinished) {
//                mTimerTv.setText(TimeTools.getCountTimeByLong(millisUntilFinished));
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        showList = new ArrayList<>();
        originalList = new ArrayList<>();
    }

    private String atShowString;

    private boolean isEnable = false;

    public void setList(String sMsgObjString, int type) {
        showList.clear();
        isEnable = false;
        if (!TextUtils.isEmpty(sMsgObjString)) {
            atShowString = sMsgObjString;

           if(sMsgObjString.indexOf("北斗") != -1){
               isEnable = true;
           }

            String bdType = SubstringUtil.subString(sMsgObjString, "BDCodeType:");
           if(TextUtils.isEmpty(bdType) || !canParseInt(bdType)){
               bdType = "0";
           }
            List<String> bCodeList = new ArrayList<>();
            bCodeList.add("BCD");
            bCodeList.add("汉字");
            showList.add(new ParamListData("服务器", 1, ""+bCodeList.get(Integer.valueOf(bdType)), bCodeList, "AT+BDCT","",isEnable));


            String bdPort = SubstringUtil.subString(sMsgObjString, "BDHWPort:");
            if(TextUtils.isEmpty(bdPort) || !canParseInt(bdPort)){
                bdPort = "0";
            }
            List<String> hardInter = new ArrayList<>();
            hardInter.add("RS232-1");
            hardInter.add("RS485-1");
            hardInter.add("RS485-2");
            hardInter.add("RS485-3");
            showList.add(new ParamListData("硬件接口", 1, ""+hardInter.get(Integer.valueOf(bdPort)), hardInter, "AT+BDPORT","",isEnable));

            String bdRate = SubstringUtil.subString(sMsgObjString, "BDBaudRate:");
            List<String> bpsList = Arrays.asList( getResources().getStringArray(R.array.rsBaudRate));
            if(TextUtils.isEmpty(bdRate) || !canParseInt(bdRate)){
                bdRate = "";
                showList.add(new ParamListData("波特率", 1, bdRate, bpsList, "AT+BDBAUD","",isEnable));
            }else {
                showList.add(new ParamListData("波特率", 1, ""+bpsList.get(Integer.valueOf(bdRate)), bpsList, "AT+BDBAUD","",isEnable));
            }

            String bdLocSw = SubstringUtil.subString(sMsgObjString, "BDLocateSW:");
            if(TextUtils.isEmpty(bdLocSw) || !canParseInt(bdLocSw)){
                bdLocSw = "0";
            }
            List<String> openOrClose = Arrays.asList( getResources().getStringArray(R.array.openOrClose));
            showList.add(new ParamListData("定位申请", 1, openOrClose.get(Integer.valueOf(bdLocSw)), openOrClose, "AT+BDLOCATE","",isEnable));


            String bdTime = SubstringUtil.subString(sMsgObjString, "BDTimeInt:");
            List<String> timeList = new ArrayList<>();
            timeList.add("0");
            timeList.add("4");
            timeList.add("6");
            timeList.add("8");
            timeList.add("12");
            timeList.add("24");
            showList.add(new ParamListData("校时间隔", 1,""+ bdTime, timeList, "AT+BDTIMEIN","",isEnable));

            if (type == Constants.AT_FROM_DEVICE) {
                originalList.addAll(showList);
            }
        }
        adapter.notifyDataSetChanged();
        recyclerView.setAdapter(adapter);
    }


    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        public MyAdapter() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_pass_way_base_item, viewGroup, false);
            return new ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.list_item.setTag(position);
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return showList == null ? 0 : showList.size();
        }


        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.list_item)
            LinearLayout list_item;
            @BindView(R.id.tv_name)
            TextView tvName;
            @BindView(R.id.edit_text)
            EditText editText;
            @BindView(R.id.img_spanner)
            ImageView imgSpanner;
            @BindView(R.id.tv_unit)
            TextView tvUnit;
            @BindView(R.id.switch_btn)
            SwitchButton switchBtn;


            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
                EditTextUtil.setEditTextNoEmoji(editText);
            }

            public void bind(int position) {
                ParamListData showListData = showList.get(position);
                tvName.setText(showListData.getName());
                switch (showListData.getType()) {
                    case 1: //spinner
                        editText.setText("" + (TextUtils.isEmpty(showListData.getValue()) ? showListData.getKey() : showListData.getValue()));
                        editText.setEnabled(showListData.isEnable());
                        if(showListData.isEnable()){
                            imgSpanner.setVisibility(View.VISIBLE);
                            editText.setBackgroundResource(R.color.white);
                            list_item.setBackgroundResource(R.color.white);
                        }else {
                            imgSpanner.setVisibility(View.GONE);
                            editText.setBackgroundResource(R.color.inputbg);
                            list_item.setBackgroundResource(R.color.inputbg);
                        }
                        tvUnit.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        list_item.setBackgroundResource(R.color.white);
                        break;
                    case 2:  // edit
                        editText.setText("" + showListData.getValue());
                        editText.setHint("请输入" + showListData.getName());
                        tvUnit.setVisibility(View.GONE);
                        imgSpanner.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        editText.setEnabled(true);//可编辑
                        editText.setVisibility(View.VISIBLE);
                        list_item.setBackgroundResource(R.color.white);
                        break;
                }
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        int curPosition = getAdapterPosition();
                        ParamListData data = showList.get(curPosition);
                        showList.set(curPosition, new ParamListData(data.getName(), data.getType(), s.toString(), data.getValues(), data.getAction(), data.getKey(), data.getIsOpen(), data.getUnit()));
                    }
                });
                imgSpanner.setTag(position);
            }

            @OnClick(R.id.img_spanner)
            public void showSpanner(View v) {
                SoftKeyBoardListener.hideKeyboard(getActivity());
                final int position = (int) v.getTag();
                final ParamListData centerData = showList.get(position);
                OptionsPickerView pickerView = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        String optionValue = centerData.getValues().get(options1);
                        editText.setText(optionValue);
                        showList.get(position).setValue(optionValue);
                    }
                })
                        .setSubmitText("确定")//确定按钮文字
                        .setCancelText("取消")//取消按钮文字
                        .build();
                pickerView.setPicker(centerData.getValues());
                pickerView.show();
            }
        }
    }


    @OnClick(R.id.btn_save)
    public void save() {
        final StringBuffer atShowResult = new StringBuffer();
        showLoading();
        BleUtils.notify(mContext,new BleNotifyCallback() {
            @Override
            public void onNotifySuccess() {
                saveResult.setLength(0);
                subPosition = 0;
                submitHandler.sendEmptyMessage(Constants.SUBMIT);
            }

            @Override
            public void onNotifyFailure(BleException exception) {
                BleLog.d("下发设置打开通知操作失败");
            }

            @Override
            public void onNotifyFailure(String message) {
                showToast(message);
                dismissProgress();
            }

            @Override
            public void onCharacteristicChanged(byte[] data) {
                for (Byte a : data) {
                    atShowResult.append(String.format("%02X", a));
                }
                String sMes = HexUtil.hexStringToString(atShowResult.toString());
                if (sMes.contains("OK")) {
                    originalList.set(subPosition - 1, showList.get(subPosition - 1));
                    atShowResult.setLength(0);
                    submitHandler.sendEmptyMessage(Constants.SUBMIT);
                }else if(sMes.contains("ERROR")){
                    atShowResult.setLength(0);
                    onError();
                }
            }

            @Override
            public void onError() {
                saveResult.append(showList.get(subPosition - 1).getName() + "保存失败" + "\r\n");
                submitHandler.sendEmptyMessage(Constants.SUBMIT);
            }

            @Override
            public void onReconSuc(String message) {
                dismissProgress();
                showToast(message);
            }
        });
    }

    public void initSettingSaveThred(final int position) {
        String url = getBlueToothUrl(showList.get(position));
        String centerName = showList.get(position).getName();
        if (TextUtils.isEmpty(url)) {
            url = "";
        }

        String originalurl = getBlueToothUrl(originalList.get(position));
        if (TextUtils.isEmpty(originalurl)) {
            originalurl = "";
        }
        if (originalurl.equals(url)) {
            submitHandler.sendEmptyMessage(Constants.SUBMIT);
            return;
        }

        mCountDownTimer.start();

        final String toSet = url;
        BleUtils.write(toSet, new BleWriteCallback() {
            @Override
            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                if (current == total) {

                }
            }

            @Override
            public void onWriteFailure(final BleException exception) {
                saveResult.append(showList.get(position).getName() + "下发失败" + "\r\n");
            }
        });


    }


    private String getBlueToothUrl(ParamListData data) {
        String name = data.getName();
        String at = data.getAction();
        String value = (data.getValue() == null) ? data.getKey() : data.getValue();
        if (TextUtils.isEmpty(value)) {
            value = "";
        }

        switch (name){
            case "北斗编码方式":
                switch (value){
                    case "BCD":
                        value = "0";
                        break;
                    case "汉字":
                        value = "1";
                        break;
                }
                break;
            case "硬件接口":
                switch (value){
                    case "RS232-1":
                        value = "0";
                        break;
                    case "RS485-1":
                        value = "1";
                        break;
                    case "RS485-2":
                        value = "2";
                        break;
                    case "RS485-3":
                        value = "3";
                        break;
                }
                break;
            case "定位申请":
                switch (value){
                    case "关闭":
                        value = "0";
                        break;
                    case "开启":
                        value = "1";
                        break;
                }
                break;
        }

        String a = "";
        try {
            a = HexUtil.chineseWordToGbk((at + "=" + value)) + "0D0A";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return a;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        submitHandler.removeCallbacksAndMessages(null);
    }


    public static boolean canParseInt(String str) {
        if (TextUtils.isEmpty(str)) { //验证是否为空
            return false;
        }
        return str.matches("-?[0-9]+.*[0-9]*");
//        return str.matches("\\d+"); //使用正则表达式判断该字符串是否为数字，第一个\是转义符，\d+表示匹配1个或 //多个连续数字，"+"和"*"类似，"*"表示0个或多个
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            LogUtil.d("终端fragment显示");
            adapter.notifyDataSetChanged();
        } else {
            //相当于OnPause()
            LogUtil.d("终端fragment隐藏");
        }
    }


    @Override
    public void onMessageEvent(FragmentChangeMessage event) {
        super.onMessageEvent(event);
        BleLog.d("FragmentChangeMessage=lora="+event.message);
        if(event.equals("北斗")){
            for (ParamListData data : showList){
                data.setEnable(true);
            }
        }else {
            if(atShowString.indexOf("北斗") == -1){
                for (ParamListData data : showList){
                    data.setEnable(true);
                }
            }
        }
    }

}
